﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;
using Db4objects.Db4o.Linq;

namespace DataLayer.Model
{
    public class Categoria
    {
        public Guid ID { get; set; }
        public string Descricao { get; set; }
        public Categoria CategoriaPai { get; set; }
        public eTipoLancamento TipoLancamento { get; set; }

        public enum eTipoLancamento
        {
            Entrada,
            Saida
        }

        public string DescricaoCompleta
        {
            get { return ToString(); }
            
        }

        public override string ToString()
        {
            StringBuilder _sb = new StringBuilder();

            /*Categoria aux = this.CategoriaPai;
            while (aux != null)
            {

            }*/

            if (this.CategoriaPai != null)
            {
                return this.CategoriaPai.ToString() + " -- " + Descricao;
            }
            return Descricao;
        }

        public void Salvar()
        {
            this.ID = Guid.NewGuid();
            IObjectContainer client = DataLayer.Core.Server.OpenClient();

            if (this.CategoriaPai != null)
            {
                this.CategoriaPai = (from Categoria p in client
                                     where p.ID == this.CategoriaPai.ID
                                     select p).Single();

                this.CategoriaPai.CategoriaPai = null;
            }

            client.Store(this);
            try
            {
                client.Commit();
            }
            catch (Exception)
            {
                client.Rollback();
            }

            DataLayer.Core.Server.CloseClient(client);
        }

        public static List<Categoria> GetAll()
        {
            IObjectContainer client = DataLayer.Core.Server.OpenClient();

            List<Categoria> _list = (from Categoria p in client
                                     select p).ToList();
            DataLayer.Core.Server.CloseClient(client);

            return _list;
        }
    }
}
